<?php

use Nette\Security as NS;

class Authenticator extends Nette\Object implements NS\IAuthenticator {

    public $connection;

    function __construct(Nette\Database\Connection $connection) {
        $this->connection = $connection;
    }

    /**
     * Performs an authentication
     * @param  array
     * @return Nette\Security\Identity
     * @throws Nette\Security\AuthenticationException
     */
    public function authenticate(array $credentials) {
        list($username, $password) = $credentials;
        $row = $this->connection->table('Users')
                        ->where('Username', $username)->fetch();

        if (!$row) {
            throw new NS\AuthenticationException('User not found.');
        }

        if ($row->Password !== md5($password)) {
            throw new NS\AuthenticationException('Invalid password.');
        }

        return new NS\Identity($row->Id);
    }

}
